/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceptingCertificate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.Process;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Maciek
 */
public class MyKeyStore {
    
    private static String keystore = "mastakeystore.jks";
    private static String storepass = "bskbsk";
    
    private static String buildCommand(String alias, String certfilepath){
        StringBuilder command = new StringBuilder();
        command.append("cmd.exe /c keytool -import -alias ");
        command.append(alias);
        command.append(" -file ").append(certfilepath);
        command.append(" -keystore ").append(keystore);
        command.append(" -storepass ").append(storepass);
        return command.toString();
    }
    
    public static void getInput(Process proc) throws IOException{
         InputStream stdout = proc.getInputStream();
        String line;
        InputStream stderr = proc.getErrorStream();
          BufferedReader brCleanUp =
        new BufferedReader (new InputStreamReader (stdout));
        
          while ((line = brCleanUp.readLine ()) != null) {
            System.out.println ("[Stdout] " + line);
          }
          brCleanUp.close();

          // clean up if any output in stderr
          brCleanUp =
            new BufferedReader (new InputStreamReader (stderr));
          while ((line = brCleanUp.readLine ()) != null) {
            System.out.println ("[Stderr] " + line);
          }
          brCleanUp.close();
    }
    
    private static int importCert(String alias, String certfilepath) throws IOException, InterruptedException{
      OutputStream stdin = null; 
      //Process process = Runtime.getRuntime().exec ("cmd.exe /c keytool -import -alias maciej -file maciej.cer -keystore mastakeystore.jks -storepass bskbsk");
      Process process = Runtime.getRuntime().exec(buildCommand(alias,certfilepath));
      stdin = process.getOutputStream (); // przechwytuje wejscia wyjscia
      stdin.write("yes\n".getBytes()); // potwierdzam, że temu certyfikatowi wierze
      stdin.flush();
      stdin.close();
      getInput(process); 
      return process.waitFor();
    }
    
    
    public static void run() throws InterruptedException{
        try {
            String alias = "maciej"; String certfilepath = "maciej.cer";
            int importCert = importCert(alias,certfilepath);
            System.out.println("Dodanie certyfiktu zakończyło się (0 == udalo sie) = " + importCert);
        } catch (IOException ex) {
            Logger.getLogger(MyKeyStore.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
